package com.yaorange.Aspect;

import com.yaorange.annotation.PermissionAnnotation;
import com.yaorange.container.PermissionContainer;
import com.yaorange.exception.BusinessException;
import com.yaorange.ma_util.util.ThreadLocalUtil;
import com.yaorange.response.enums.ResultCode;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Aspect
@Component
public class PermissionAspect {
    @Autowired
    PermissionContainer permissionContainer;


    @Around("@annotation(permissionAnnotation)")
    public Object permissionChecked(ProceedingJoinPoint joinPoint,PermissionAnnotation permissionAnnotation) throws Throwable {
        HashMap map = ThreadLocalUtil.get();
        Integer id = (Integer)map.get("userId");
        Set<String> strings = permissionContainer.get("LOGIN_USER_" + id.toString());
        if (strings != null && strings.contains(permissionAnnotation.value())){
            Object proceed = joinPoint.proceed();
            return proceed;
        }
        throw new BusinessException(ResultCode.FORBIDDEN);
    }
}
